<?php
namespace swift\template\taglib;

use swift\template\TagLib;

/**
 * swiftshop自定义标签
 * @package swift\template\taglib
 */

class Sw extends TagLib{
    // 标签定义
    protected $tags = [
        'createpage'          =>  ['attr' => 'count,page' , 'close' => 0],
        'first'               =>  ['attr' => 'name,key'],
        'last'                =>  ['attr' => 'name,key'],
    ];

    /**
     * 自动生成分页样式
     * @param $tag
     * @param $content
     * @return string
     */
    public function tagCreatepage($tag, $content){
        $count = $tag['count'];  // 总页数
        $page = $tag['page'];   // 当前页码

        if (empty($page)) {
            $page = 1;
        }

        if (!empty($count)) {
            $str = '<option value=\'1\'>1</option>';
            $min = min($count - 1, $page + 3);

            for ($i = $page - 3; $i <= $min; $i++) {
                if ($i < 2) {
                    continue;
                }

                $str .= '<option value=\'' . $i . '\'';
                $str .= ($page == $i ? ' selected=\'true\'' : '');
                $str .= '>' . $i . '</option>';
            }

            if (1 < $count) {
                $str .= '<option value=\'' . $count . '\'';
                $str .= ($page == $count ? ' selected=\'true\'' : '');
                $str .= '>' . $count . '</option>';
            }
        }
        else {
            $str = '';
        }

        return $str;
    }

    public function tagFirst($tag , $content){
        $key = $tag['key'];
        $parseStr = '<?php if('.$key.' == 0): ?>' . $content . '<?php endif; ?>';
        return $parseStr;
    }

    public function tagLast($tag , $content){
        $key = $tag['key'];
        $arr = $tag['name'];
        $parseStr = '<?php if(('.$key.'+1) == count('.$arr.')): ?>' . $content . '<?php endif; ?>';
        return $parseStr;
    }
}